package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.AcquireAccountTokenReq;
import net.ib.mntalk.protocol.Session.AcquireAccountTokenRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.MTalkIntent;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.ui.start.AccountIdActivity;
import net.ib.mtalk.ui.start.AccountPhoneActivity;
import net.ib.mtalk.ui.start.AuthenticationActivity;
import net.ib.mtalk.ui.start.NameActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

public class AcquireAccountTask extends AsyncNetTask {

	private AcquireAccountTokenReq mAcquireAccountTokenReq;
	
	public AcquireAccountTask(Context context, Handler handler, AcquireAccountTokenReq acquireAccountTokenReq) {
		super(context, handler);
		mAcquireAccountTokenReq = acquireAccountTokenReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		
		TcpEnvelope revelop = new TcpEnvelope.Builder()
			.setMessage(mAcquireAccountTokenReq)
			.setMethodId(Session.Registration.AcquireAccountToken)
			.setType(TcpEnvelope.REQUEST)
			.build();
		MTalkLogWriter.d("SEND RESULT AcquireAccountToken");
		
		return revelop;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		MTalkLogWriter.d("AcquireAccountAuthTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage( HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		AcquireAccountTokenRes acquireAccountTokenRes = (AcquireAccountTokenRes) resultEnvelope.getMessage();
		
		if(acquireAccountTokenRes.getResponseCode() == Common.SUCCESS){
			if( (mContext instanceof AuthenticationActivity && !((AuthenticationActivity)mContext).mExistRedirect)
					|| (mContext instanceof AccountPhoneActivity && !((AccountPhoneActivity)mContext).mExistRedirect) )
			{
				Intent i = new Intent(mContext, NameActivity.class);
				i.putExtra(MTalkIntent.KEY_ACCOUNT_TOKEN, acquireAccountTokenRes.getAccountToken().toByteArray());
				((Activity)mContext).finish();
				mContext.startActivity(i);
			}
			else
			{
				Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_SUCCESS);
				msg.obj = acquireAccountTokenRes.getAccountToken();
				mUiHandler.sendMessageAtFrontOfQueue(msg);
			}
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_FAIL));
		}
	}

	
}
